import { action, runInAction, set, transaction } from "mobx"
import { AuthStore } from "./AuthStore"
import _ from 'lodash'

interface LoginInfo {
    loginName: string
    loginPwd: string
}

export default class Auth {
    private _store: AuthStore

    constructor(stores: any) {
        const { auth } = stores
        this._store = auth
    }

    @action
    checkLocalStage() {
        let payload = $store.getItem("token")
        if (!payload) {
            runInAction(() => {
                // this._store.isLogin = false
                set(this._store, {
                    currentUser: undefined,
                    token: undefined,
                    tokenHead: undefined,
                })
            })
            return false
        }

        payload = JSON.parse(payload)
        const currentUser = JSON.parse(_.get(payload, 'currentUser'))
        const token = _.get(payload, 'token')
        const tokenHead = _.get(payload, 'tokenHead')

        runInAction(() => {
            set(this._store, {
                currentUser: currentUser,
                token: token,
                tokenHead: tokenHead,
            })
        })
        return true
    }

    /**
     * 登录
     */
    @action
    async login(loginInfo: LoginInfo) {
        await $api.request('/user/login.json', {
            method: 'post',
            params: loginInfo,
            timeout: 1000 * 30

        }).then(res => {
            if (res.data) {
                if (res.data.success) {
                    const payload = res.data.data
                    $store.setItem("token", JSON.stringify(payload))

                    const currentUser = JSON.parse(_.get(payload, 'currentUser'))
                    const token = _.get(payload, 'token')
                    const tokenHead = _.get(payload, 'tokenHead')

                    runInAction(() => {
                        // this._store.isLogin = true
                        set(this._store, {
                            currentUser: currentUser,
                            token: token,
                            tokenHead: tokenHead,
                        })
                    })
                }
            }
        })
    }

    @action
    async logout() {
        set(this._store, {
            // this._store.isLogin = false
            currentUser: undefined,
            token: undefined,
            tokenHead: undefined,
        })
        await $api.invokeApi('/user/logout')
    }
}